﻿/**
 *  if have any question pleas email me wzyuliyang911@gmail.com
 *
 */

#include "initrect.h"
using namespace MyInitRectNameSpace;

InitRect::InitRect(String MatFilename, String windowName)
{
    _MatFileName = MatFilename;
    img = imread(_MatFileName.c_str ());
    _windowName = windowName;
}

InitRect::InitRect(Mat InputMat, String windowName)
{
    InputMat.copyTo (img);
    _windowName = windowName;
}

InitRect::~InitRect()
{
    cvSetMouseCallback(_windowName.c_str (), NULL, NULL);
}

void InitRect::mouseHandler(int event, int x, int y, int flags, void *param)
{
    if (event == CV_EVENT_LBUTTONDOWN && !drag)
    {
        point1 = Point(x, y);
        drag = 1;
    }
    if (event == CV_EVENT_MOUSEMOVE && drag)
    {
        Mat img1 = img.clone();
        point2 = Point(x, y);
        rectangle(img1, point1, point2, CV_RGB(255, 0, 0), 1, 8, 0);
        imshow(_windowName.c_str (), img1);
    }
    if (event == CV_EVENT_LBUTTONUP && drag)
    {
        point2 = Point(x, y);
        if(point2.x < point1.x){
            rect = Rect(point2.x,point2 .y,abs(x-point1.x),abs(y-point1.y));
        }else{
            rect = Rect(point1.x,point1.y,abs(x-point1.x),abs(y-point1.y));
        }
        drag = 0;
        roiImg = img(rect);
    }
    if (event == CV_EVENT_LBUTTONUP)
    {
        select_flag = 1;
        drag = 0;
    }
}

Rect InitRect::Select()
{
    namedWindow (_windowName.c_str ());
    cvSetMouseCallback(_windowName.c_str (), mouseHandler, NULL);
    imshow(_windowName.c_str (), img);
    while(cv::waitKey(1) != 27){
//        std::cout<<rect.x<<"---"<<rect.y<<"---"<<rect.width<<"---"<<rect.height<<std::endl;
    }
    return rect;
}

